import numpy
import os.path
from pathlib import Path

import oss2
import torch
import scipy.io.wavfile as wavf
from esp.utils.configHandler import Config

conf = Config()


class Saver:
    def __init__(self, rate: int, local_path: str):
        self.default_rate = rate
        self.default_local_path = local_path
        # self.conf=Config()

    def save_wav(self, sentence: str, wav_data: torch.Tensor):
        format_file_path = get_format_filepath(sentence)
        save_wav_tensor_with_filepath(wav_data, format_file_path)

    def save_wav_upload_oss(self, sentence: str, wav_data: torch.Tensor):
        format_file_path = get_format_filepath(sentence)
        save_wav_tensor_with_filepath_and_oss(wav_data, format_file_path)

save_ = Saver(rate=conf.rate, local_path=conf.local_path)


def get_format_filepath(sentence: str, local_path: str = save_.default_local_path) -> str:
    if not Path(local_path).exists():
        os.mkdir(local_path)
    if len(sentence) > 20:
        sentence = sentence[:19]
    if not Path(local_path + sentence + '.wav').exists():
        return local_path + sentence + '.wav'
    for i in range(1, 99):
        if not Path(local_path + sentence + '_{}.wav'.format(i)).exists():
            return local_path + sentence + '_{}.wav'.format(i)


def save_wav_tensor_with_filepath(wav_data: torch.Tensor, filepath: str, rate: int = conf.rate) -> bool:
    # try:
    #     wavf.write(filepath, rate, wav_data.view(-1).numpy())
    # except Exception as e:
    #     return False
    wavf.write(filepath, rate, wav_data.view(-1).cpu().numpy())
    return True


def save_wav_tensor_with_filepath_and_oss(wav_data: torch.Tensor, filepath: str, rate: int = conf.rate) -> bool:
    # try:
    #     wavf.write(filepath, rate, wav_data.view(-1).numpy())
    # except Exception as e:
    #     return False
    wavf.write(filepath, rate, wav_data.view(-1).cpu().numpy())
    upload_file_to_oss(filepath)
    return True


def upload_file_to_oss(file_path: str):
    with open(file_path, 'rb') as file_object:
        auth = oss2.Auth(conf.accesskey, conf.secret)
        bucket = oss2.Bucket(auth, conf.endpoint, 'masaikk2')
        bucket.put_object('esp/' + os.path.split(file_path)[1], file_object)


if __name__ == '__main__':
    upload_file_to_oss('/tmp/2.txt')
